package pencil.controller;

import java.sql.SQLException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pencil.service.pencil_service;
import pencil.to.blackSimTO;
import pencil.to.cuttingMachineTO;
import pencil.to.holeNamuTO;
import pencil.to.insertMachineTO;
import pencil.util.pencilUtil;

//
/**
 * 홈파인 나무판에 연필심 넣는 머신
 * insert머신에서 넘어온 것을 깍는다.
 *
 */
@Controller
@RequestMapping("/cuttingMachine")
public class cuttingMachineController {
private pencil_service service;
	
	public void setService(pencil_service service){
		this.service= service;
	}
	
	@RequestMapping("/begin.do")
	public ModelAndView begin(int orderNumS) throws SQLException, InterruptedException{
		//0. 주문량에 필요한 재료계산
		int blackboard=orderNumS;
		int normal=0;//성공된 제품의수
		int abnormal=0;//비정상 품
//		기계상태 가져오기
		cuttingMachineTO cmto = service.selectCuttingMInfo();
		
		if(cmto==null){
			cmto = new cuttingMachineTO();
		}
		
		int machineLife = cmto.getMachineLife();
		
		System.out.println("재료 공정 시작");
		
		
		
//		hmto.setBoard(namuNeed);
		cmto.setRunstep(0);
		
		
		cmto.setStartTime(pencilUtil.getNow());//시작시간
		
		int run = 0;
		while(run<=5){
			
			
			//작동시간//
			Thread.sleep(1000);
			//
			cmto.setRunstep(run++);
			System.out.println("진행률:"+(int)cmto.getRunstep());
		}	
		
		cmto.setEndTime(pencilUtil.getNow());
		int testValue=pencilUtil.troubleMaker(5, 5);//불량률 조절 매서드(기본값, 랜덤값)
	//		System.out.println("불량률:"+testValue );
		
		if(testValue>=7){//불량률 판별
			normal=normal+1;//성공품 증가
			
		}else{
			abnormal=abnormal+1;
				
		}
			
		machineLife++;
			
			
			
		cmto.setBlackBoard(blackboard);
		cmto.setNormal(normal);
		cmto.setMachineLife(machineLife);
		cmto.setAbnormal(abnormal);
		
//		    불량처리해야함	
			if(abnormal==0){
				cmto.setState("정상");
			}else{
				cmto.setState("불량");
			}
			
			

			System.out.println("블랙보드 개수 : " + orderNumS);
			System.out.println("정상품 개수 " + normal);
			System.out.println("불량품 개수 " + abnormal);
			
		
	
			service.insertCuttingMInfo(cmto);
			
		
		
	
		System.out.println(cmto);
	
		
	return null;
			
	}
	
}
